<template>
  <view class="comment-input-container">
    <!-- 回复提示 -->
    <view v-if="replyTo" class="reply-to">回复 {{ replyTo }}:</view>
    <!-- 输入框 -->
    <input
        :placeholder="replyTo ? `回复 ${replyTo}` : '我也来说一句'"
        v-model="commentText"
        @confirm="handleComment"
        confirm-type="send"
        class="comment-input"
    />
    <view class="refresh">
      <u-icon name="reload" size="24"></u-icon>
    </view>
    <button class="send-button" @click="handleComment">发送</button>
  </view>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue';
import { addComment } from '@/apis/homeAPI';

// 接收回复信息、父评论ID和文章ID
const props = defineProps({
  replyTo: {
    type: String,
    default: ''
  },
  parentCommentId: {
    type: Number,
    default: 0
  },
  articleId: {
    type: Number,
    required: true
  }
});

// 触发刷新和清空事件
const emit = defineEmits(['send-comment', 'clear-reply']);

// 评论内容
const commentText = ref('');

// 发送评论
const handleComment = async () => {
  const content = commentText.value.trim();
  if (!content) {
    uni.showToast({ title: '请输入内容', icon: 'none' });
    return;
  }
  // 构建评论数据
  const commentData = {
    articleId: props.articleId,
    userId: 3,
    content: content,
    parentCommentId: props.parentCommentId,
    createTime: new Date().toISOString()
  };
  try {
    await addComment(commentData);
    uni.showToast({ title: '发送成功', icon: 'none' });
    emit('send-comment'); // 通知刷新评论
    emit('clear-reply'); // 清空回复状态
    commentText.value = '';
  } catch (error) {
    console.error('发送失败:', error);
    uni.showToast({ title: '发送失败', icon: 'none' });
  }
};
</script>

<style scoped lang="scss">
.comment-input-container {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f5f5f5;
  .reply-to {
    font-size: 14px;
    color: #666;
    margin-right: 8px;
  }
  .comment-input {
    flex: 1;
    padding: 10px 15px;
    border-radius: 20px;
    background-color: #fff;
    font-size: 14px;
  }
  .refresh {
    margin: 0 10px;
  }
  .send-button {
    padding: 8px 15px;
    border-radius: 20px;
    background-color: #007bff;
    color: #fff;
    font-size: 14px;
    border: none;
  }
}
</style>